using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using VOL.Core.Filters;
using VOL.Core.Utilities;
using VOL.Core.Enums;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Entity.AttributeManager;

namespace VOL.WebApi.Controllers.demo
{
    [Route("api/demo/[controller]")]
    [ApiController]
    [PermissionTable(Name = "productinformationmodel")]
    [Microsoft.AspNetCore.Authorization.AllowAnonymous]  // 允许匿名访问，去掉JWT验证
    public class ProductInformationController : ControllerBase
    {
        private readonly IproductinformationmodelService _service;

        public ProductInformationController(IproductinformationmodelService service)
        {
            _service = service;
        }

        /// <summary>
        /// 添加新产品
        /// </summary>
        /// <param name="product">产品信息</param>
        /// <returns>添加结果</returns>
        [HttpPost("Add")]
        [ApiActionPermission(ActionPermissionOptions.Add)]
        public async Task<ActionResult<WebResponseContent>> AddProduct([FromBody] productinformationmodel product)
        {
            if (product == null)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = "请求参数不能为空" });
            }

            // 基础参数验证
            if (string.IsNullOrEmpty(product.goodsCode))
            {
                return BadRequest(new WebResponseContent { Status = false, Message = "产品编号不能为空" });
            }

            if (string.IsNullOrEmpty(product.goodsName))
            {
                return BadRequest(new WebResponseContent { Status = false, Message = "产品名称不能为空" });
            }

            // 添加产品信息
            var result = await _service.AddProductAsync(product);
            return Ok(result);
        }

        /// <summary>
        /// 检查产品编号是否已存在
        /// </summary>
        /// <param name="goodsCode">产品编号</param>
        /// <returns>存在返回true，不存在返回false</returns>
        [HttpGet("CheckProductCode")]
        public async Task<ActionResult<bool>> CheckProductCode(string goodsCode)
        {
            if (string.IsNullOrEmpty(goodsCode))
            {
                return false;
            }

            return await _service.IsProductCodeExistsAsync(goodsCode);
        }

        /// <summary>
        /// 获取产品详情
        /// </summary>
        /// <param name="productId">产品ID</param>
        /// <returns>产品详细信息</returns>
        [HttpGet("Detail/{productId}")]
        public async Task<ActionResult<productinformationmodel>> GetProductDetail(long productId)
        {
            if (productId <= 0)
            {
                return BadRequest("产品ID不能为空");
            }

            var product = await _service.GetProductByIdAsync(productId);
            if (product == null)
            {
                return NotFound(new { Message = "未找到产品信息" });
            }

            return Ok(product);
        }

        /// <summary>
        /// 获取货品选项列表（用于下拉选择）
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <returns>货品选项列表</returns>
        [HttpGet("Options")]
        public async Task<ActionResult> GetProductOptions(string keyword = null, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var result = await _service.GetProductOptionsAsync(keyword, pageIndex, pageSize);
                
                var response = new 
                {
                    success = true,
                    data = result.Data.Select(p => new 
                    {
                        id = p.Id,          // 货品ID
                        goodsCode = p.goodsCode,    // 货品编号
                        goodsName = p.goodsName,    // 货品名称
                        specModel = p.specModel,    // 规格型号
                        purchasePrice = p.purchasePrice,  // 入库参考价
                        salePrice = p.salePrice,    // 出库参考价
                        currentInventory = p.currentInventory  // 当前库存
                    }),
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize
                };
                
                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"获取货品列表失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有可用货品列表（简化版本，用于快速获取ID和名称）
        /// </summary>
        /// <returns>货品ID和名称列表</returns>
        [HttpGet("List")]
        public async Task<ActionResult> GetProductList()
        {
            try
            {
                // 获取所有未删除的货品
                var result = await _service.GetProductOptionsAsync(null, 1, 1000);
                
                var response = new 
                {
                    success = true,
                    data = result.Data.Where(p => p.IsDel == 0).Select(p => new 
                    {
                        id = p.Id,                  // 货品ID（这是其他表中的GoodsId）
                        goodsCode = p.goodsCode,    // 货品编号  
                        goodsName = p.goodsName,    // 货品名称
                        value = p.Id,               // 用于前端select组件的value
                        label = $"{p.goodsCode} - {p.goodsName}"  // 用于前端select组件的label
                    }),
                    message = "获取货品列表成功"
                };
                
                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"获取货品列表失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 分页查询货品详细信息（包含货品类型、供应商、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <param name="keyword">货品名称或编号（模糊搜索）</param>
        /// <param name="productTypeId">货品类型ID（精确匹配）</param>
        /// <param name="supplierId">供应商ID（精确匹配）</param>
        /// <param name="userId">客户ID（精确匹配）</param>
        /// <param name="status">状态（精确匹配）</param>
        /// <param name="orderBy">排序字段（goodsName/goodsCode/purchasePrice/salePrice/currentInventory/createDate）</param>
        /// <param name="orderDirection">排序方向（asc/desc）</param>
        /// <returns>分页查询结果</returns>
        [HttpGet("PagedWithDetails")]
        public async Task<ActionResult<ProductQueryResult>> GetProductsWithDetails(
            int pageIndex = 1,
            int pageSize = 20,
            string keyword = null,
            int? productTypeId = null,
            long? supplierId = null,
            int? userId = null,
            sbyte? status = null,
            string orderBy = "CreateDate",
            string orderDirection = "desc")
        {
            try
            {
                var request = new ProductQueryRequest
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    Keyword = keyword,
                    ProductTypeId = productTypeId,
                    SupplierId = supplierId,
                    UserId = userId,
                    Status = status,
                    OrderBy = orderBy,
                    OrderDirection = orderDirection
                };

                var result = await _service.GetProductsWithDetailsAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new ProductQueryResult 
                { 
                    Success = false, 
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<ProductWithDetailsDto>(),
                    TotalCount = 0
                });
            }
        }

        /// <summary>
        /// POST方式分页查询货品详细信息（支持复杂查询参数）
        /// </summary>
        /// <param name="request">查询请求参数</param>
        /// <returns>分页查询结果</returns>
        [HttpPost("QueryWithDetails")]
        public async Task<ActionResult<ProductQueryResult>> QueryProductsWithDetails([FromBody] ProductQueryRequest request)
        {
            try
            {
                if (request == null)
                {
                    return BadRequest(new ProductQueryResult 
                    { 
                        Success = false, 
                        Message = "查询参数不能为空",
                        Data = new List<ProductWithDetailsDto>(),
                        TotalCount = 0
                    });
                }

                var result = await _service.GetProductsWithDetailsAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new ProductQueryResult 
                { 
                    Success = false, 
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<ProductWithDetailsDto>(),
                    TotalCount = 0
                });
            }
        }
    }
}
